'''
Created on Aug 29, 2011

@author: david
'''
import os
from string import Template

prompts = ["   App Name: ",
           "Folder Name: ",
           " REST (y/n): "]

keys = ["app","folder","rest"]

class NewApp(object):

    def __init__(self):
        """
        Constructor
        """
        print "New PspyGear App\n"
    
    def run(self):
        "do it"
        args = self._gatherInput()
        self._buildApp(args)
        
    def _buildApp(self,args):                             
        """
        Build the app from user input
        and files in prototype.
        """
        # directory structure
        print "-- Creating Directories..."
        os.makedirs("./app/%s/actions" % args["folder"])
        os.makedirs("./web/%s/" % args["folder"])
        
        # python packages
        print "-- Creating Packages..."
        self._createPyPkg("./app/%s/__init__.py" % args["folder"] )
        self._createPyPkg("./app/%s/actions/__init__.py" % args["folder"])
        
        # domain
        print "-- Creating Domain..."
        self._createDomain(args)
        
        # dispatch
        print "-- Modifying dispatch.py..."
        self._modifyDispatch(args)
        
        # Index files
        print "-- Creating Index files..."
        self._placeIndexFiles(args)
        
        #done
        print "Done!"
        
    def _createPyPkg(self,path):
        """
        Create the package files.
        """
        f = open(path,"w+")
        f.write("# generated package file")
        f.close()
                        
    def _createDomain(self,args):
        """
        Create RequestHandler for
        Action Domain.
        """
        f = open("./scripts/prototype/domain.py")
        tmplt = Template(f.read())
        f.close()
        
        f = open("./app/%s/domain.py" % args['folder'],"w+")
        f.write(tmplt.substitute(args))
        f.close()
        
    def _modifyDispatch(self,args):
        """
        Add request handlers to dispatch module.
        """             
        f = open("./dispatch.py")
        txt = f.readlines()
        f.close()
        imps = apps = False
        
        # standard applet takes all comers to initial node
        # (manages static data from /html dir)
        aplts = "('/%s/.*',%sRH)" % (args['app'],args['app'])
        if args['rest'].lower().startswith('y'):
            # REST style stops at name
            aplts = "%s,('/%s',%sRH)," % (aplts,args['app'],args['app'])
         
        # rewrite module with mods
        f = open("./dispatch.py","w+")
        for line in txt:
            f.write("%s" % line)
            if not imps and line.startswith("from pspy"):
                f.write("from app.%s.domain import AppletRH as %sRH\n" % (args['folder'],args['app']))
                imps = True
            if not apps and line.startswith("APPLETS"):
                f.write("%s\n" % aplts)
                apps = True
        
        # and, done
        f.close()
        
    def _placeIndexFiles(self,args):
        """
        Create default action / page
        """
        # Action file
        f = open("./scripts/prototype/index.py")
        txt = Template(f.read())
        f.close()
        
        f = open("./app/%s/actions/index.py" % args['folder'],"w+")
        f.write(txt.substitute(args))
        f.close()

        # Page file (genshi!)
        f = open("./scripts/prototype/Index.gen")
        txt = Template(f.read())
        f.close()
        
        f = open("./web/%s/Index.gen" % args['folder'],"w+")
        f.write(txt.substitute(args))
        f.close()

    def _gatherInput(self):
        """
        Ask and gather
        """
        vals = []        
        for p in prompts:
            vals.append(raw_input(p))
    
        return dict(zip(keys,vals))
    
if __name__ == '__main__':
    na = NewApp()
    na.run()
    
        
